<template>
  <div class="container">
    <div class="subject">
      <el-text>学科：</el-text>
      <el-radio-group @change="subject_change" v-model="state.subject_id">     
        <el-radio-button :label="item.value" v-for="(item, index) in subjectList" :key="index">
          {{ item.name }}
        </el-radio-button>
      </el-radio-group>
    </div>
    <div class="has_applied">
      <el-text>是否申请过</el-text>
      <el-radio-group @change="apply_type_change" v-model="state.applied_type">     
        <el-radio-button :label="item.value" v-for="(item, index) in revisable_apply_select_list" :key="index">
          {{ item.name }}
        </el-radio-button>
      </el-radio-group>
    </div>
    <div class="card-list scroll-container" @scroll="handleScroll" v-loading="isLoadingMore">
      <el-card v-for="(item, index) in questionList" :key="index" class="card-item">
        <template #header>
          <div class="card_header">
            <el-text>{{ item.reference }}</el-text>
            <el-text class="text_red">{{ item.status }}</el-text>
          </div>
        </template>
        <div class="card_content">         
          <div v-html="item.content_front" class="line-break"></div>
          <div class="twoItem">
            <el-button type="success" @click="onclickCard(item)">{{ applied_type_dic[parseInt(state.applied_type) -1] }}</el-button>
            <el-text class="expiration">截止日期：{{ item.expiration.slice(0, 10) }}</el-text>
          </div>
        </div>
      </el-card> 
    </div>
    <el-drawer v-model="drawerUploadVideo" direction="rtl">
      <template #header>
        <h4>上传视频</h4>
      </template>
      <template #default>
        <div>
          <el-radio v-model="radio1" value="Option 1" size="large">
            Option 1
          </el-radio>
          <el-radio v-model="radio1" value="Option 2" size="large">
            Option 2
          </el-radio>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawerUploadVideo=false">取消</el-button>       
        </div>
      </template>
    </el-drawer>
    <el-dialog
      v-model="popup"
      title="申请"
      width="500"
    >
      <span>确定要为该试题申请微视频解析吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="popup = false">取消</el-button>
          <el-button type="primary" @click="onConfirmPopup()">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import axios from '@/utils/axios'
//import { postQuestionVideoPermitAPI, getQuestionVideoPermitAPI } from '@/utils'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
// 通用变量
const state = reactive({
  select_question_id: 0,
  subject_id: 1,
  applied_type: 2,
  page: 1,
  size: 10,
  total: 1,
})
// 申请上传视频
const drawerUploadVideo = ref()
// 申请视频解析弹窗
const popup = ref()
// 弹窗关闭处理事件
const onClosePopup = () => {
  popup.value.close()
}
// 弹窗确定事件, 申请录入试卷的权限，并刷新当前的试卷列表
const onConfirmPopup = () => {
  console.log('点击了确定', state.select_question_id)
  postPerimit()
  popup.value = false
  getQuestionVideoPermitData()
}
const isLoadingMore = ref(false);
// 显示到页面的可录入的试卷，且未过期
const questionList = ref([])
const questionListId = ref([])
const applied_type_dic = ['未批准', '去申请', '去解析']
// 可录入试卷的是否申请过选择框选项
const revisable_apply_select_list = ref([
  { name: '已申请', value: '1', checked: false },
  { name: '未申请', value: '2', checked: true },
  { name: '已批准', value: '3', checked: false },
])
// 可选择的学科选项
const subjectList = ref([
  { name: '信息', value: '1', checked: true },
  { name: '通用', value: '2', checked: false },
  { name: '职高', value: '3', checked: false },
])


/**读取试题视频申请列表请求 */
function  getQuestionVideoPermitAPI (params) {
  console.log('读取试题视频申请列表请求的参数', params)
  axios.get('/questions/get_permit_question_video/', {params}).then(res => {
    console.log('get_permit_question_video:', res)
    if (res.code == 200) {
      questionList.value = res.data.results
      state.total = res.total
    } else {
      questionList.value = []     
      ElMessage({
        message: '读取失败',
        type: 'error',
      })
    }
  }).catch((error)=>{
    console.log("读取试题视频申请列表请求错误：", error)
  })
}
// 根据学科、不同申请类型获取题目列表
const getQuestionVideoPermitData = () => {
  let data = {
    applied_type: state.applied_type,
    subject_id: state.subject_id,
    page: state.page,
    size: state.size,
  }
  getQuestionVideoPermitAPI(data)
}
// 学科改变了,重新获取该学科的知识点
const subject_change = () => {
  console.log('学科改变：')
  state.page = 1
  getQuestionVideoPermitData()
}
// 选择了不同状态
const apply_type_change = () => {
  console.log('申请状态改变了')
  state.page = 1
  getQuestionVideoPermitData()
}
/** 提交用户申请试卷视频解析的权限 */
const postQuestionVideoPermitAPI = (params) => {
  axios.post(`/questions/create_permit_question_video/`, params).then(res => {
    return res
  }).catch((error)=>{
    console.log("申请视频解析错误：", error)
  })
}
// 发送申请试卷允许录入权限
const postPerimit = async () => {
  const data = {
    question: state.select_question_id,
  }
  const res = postQuestionVideoPermitAPI(data)
  console.log('提交申请解析权限', res)
  if (res.code === 200) {
    ElMessage({
      message: '提交成功',
      type: 'success',
    })
  } else if (res.code === 1022) {
    ElMessage({
      message: '你已经申请过，联系管理员审批',
      type: 'error',
    })
  } else {
    ElMessage({
      message: '提交错误！',
      type: 'error',
    })
  }
}
// 点击卡片事件，如果是用户申请过的，则进入第二步页面具体试题；否则进入申请页面
const onclickCard = (question) => {
  console.log('点击卡片页面', question)
  state.select_question_id = question.id
  if (question.status == '未申请') {
    console.log('未申请，现在去申请', question.id)
    drawerUploadVideo.value = true
  } else if (question.status == '申请过') {
    console.log('管理员未审批', question.id)
    ElMessage({
      message: '管理员未审批',
      type: 'error',
    })
  } else if (question.status == '已批准') {

    console.log('已批准，弹窗上传文件')
  }
}
// 添加更多可录入试题列表，且未过期，用于上拉触底新增数据
const addMorePeimitQuestionVideoData = async () => {
  const data = {
    applied_type: state.applied_type,
    subject_id: state.subject_id,
    page: state.page + 1,
    size: state.size,
  }
  const res = getQuestionVideoPermitAPI(data)
  console.log('获取更多试题', res)
  if (res.code == 200) {
    questionList.value.push(...res.data.results)
    state.page += 1
    state.total = res.total
  } else {
    ElMessage({
      message: '没有更多了',
      type: 'warning',
    })
  }
}
// 页面加载
onMounted(() => {
  console.log('页面加载')
  getQuestionVideoPermitData()
})
//监听路由变化
const unWatch = router.beforeEach((to, from, next) => {
  getQuestionVideoPermitData()
})
onUnmounted(()=>{
    unWatch()
})
// 处理滚动事件，如果触底则加载更多内容
const handleScroll = async(event) => {
  const { scrollTop, scrollHeight, clientHeight } = event.target
  if (scrollTop + clientHeight >= scrollHeight - 5 && !isLoadingMore.value) { // 减5是为了避免误差
    isLoadingMore.value = true;
    if (questionList.value.length >= state.total) {
      ElMessage({
        message: '没有更多试题了',
        type: 'warning',
      })   
    } else {      
      await Promise.all([addMorePeimitQuestionVideoData()])
    }
    isLoadingMore.value = false;
  }
}
</script>
<style lang="scss" scoped>
.card_content {
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
}

.container {
  font-size: 28rpx;
}

.subject,
.has_applied {
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: left;
}
.line-break{
  white-space: pre-wrap;
  width: 950px;
  font-size: 12px;
  }
  .scroll-container {
  height: 400px; /* 设置一个固定的高度 */
  overflow-y: auto; /* 开启滚动 */
  position: relative;
}
.loading-more {
  text-align: center;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
}
.card_header {
  padding: 3px;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}
.text_red {
  color:red;
}
.twoItem {
  margin: 4px;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-around;
}
</style>